<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏大厅</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_hall.css">
</head>
<body>
    <div>
        <!-- 导航栏 -->
        <div class="nav"><a href="./login.html">五子棋对战</a></div>
        <!-- 这个页面的容器元素 -->
        <div class="container">

            <div class="q2">
                <!-- 展示用户信息 -->
                <div id="screen"></div>
                <div class="bu">
                    <!-- 匹配按钮 -->
                    <div id="match-button">开始匹配</div>
                    <!-- AI对战按钮 -->
                    <div id="ai-match-button">AI对战</div>
                </div>
                
            </div>
        </div>

    </div>

    <script src="js/jquery.min.js"></script>
    
    <script>

        $.ajax({
            method: 'get',
            url: 'userInfo',
            success: function(data) {
                //console.log(data);
                let screen = document.querySelector('#screen');
                screen.innerHTML = '玩家: ' + data.username + ', 分数: ' + data.score +
                "<br> 比赛场次: " + data.totalCount + ", 获胜场次: " + data.winCount;
            },
            error: function(){
                alert("获取用户信息失败!");
            }
        });

        //初始化WebSocket，并实现前端逻辑
        let url = 'ws://'+ location.host + '/findMatch';
        let websocket = new WebSocket(url);
        websocket.onopen = function(){
            console.log("open...");
        }
        websocket.onclose = function(){
            console.log("close...");
            
        }
        websocket.onerror = function(){
            console.log("error...");
        }
        
        //点击开始匹配 
        //1.玩家对战
        let matchButton = document.querySelector("#match-button");
        matchButton.onclick = function(){
            if(websocket.readyState == websocket.OPEN){
                if(matchButton.innerHTML == '开始匹配'){
                    console.log("开始匹配");
                    websocket.send(JSON.stringify({
                        message: 'startMatch'
                    }));
                }else if(matchButton.innerHTML == '匹配中...(点击取消)'){
                    console.log('取消匹配!');
                    websocket.send(JSON.stringify({
                        message: 'stopMatch'
                    }));
                }
            }else{
                alert("当前你的连接已经断开，请重新登入");
                location.replace("/login.html");
            }
        }
        //2.AI对战
        let aiMatchButton = document.querySelector("#ai-match-button");
        aiMatchButton.onclick = function(){
            websocket.send(JSON.stringify({
                message: 'aiMatch'
            }));
        }
        
        //处理服务器响应
        websocket.onmessage = function(e){
            //将返回的JSON字符串解析为js对象
            let resp = JSON.parse(e.data);
            if(!resp.ok){
                console.log('游戏大厅中发生错误: ' + resp.reason);
                location.replace("/login.html");
                return;
            }
            if(resp.message == 'startMatch'){
                console.log('进入匹配队列成功!');
                matchButton.innerHTML = '匹配中...(点击取消)';
            }else if(resp.message == 'aiMatch'){//AI对战
                console.log('AI对战开始');
                location.replace('/game_room.html');
            }else if (resp.message == 'stopMatch') {
                console.log('离开匹配队列成功!');
                matchButton.innerHTML = '开始匹配';
            }else if (resp.message == 'matchSuccess') {
                console.log('匹配成功! 进入游戏页面!');
                location.replace('/game_room.html');
            }else if (resp.message == 'repeatConnection'){
                alert("账号已在其他地方登入，请退出重试");
                location.replace("/login.html");
            }else {
                console.log('非法的 message: ' + resp.message);
            }
        }

        // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function(){
            websocket.close();
        }
    </script>
</body>
</html>